import { h } from "vue";
import error_ico from "@/assets/imgs/error_ico.png";
import success_ico from "@/assets/imgs/success_ico.png";
import warning_ico from "@/assets/imgs/warning_icon.png";

export const errorTips = (message: string) => {
  // @ts-ignore
  ElMessage({
    message,
    type: "error",
    dangerouslyUseHTMLString: true,
    customClass: "test-ElMessage",
    offset: 100,
    icon: h("img", {
      src: error_ico,
      style: {
        width: "16px",
        height: "16px",
        marginRight: "10px",
      },
    }),
    // duration: 0,
  });
};

export const successTips = (message: string) => {
  // @ts-ignore
  ElMessage({
    message,
    type: "success",
    dangerouslyUseHTMLString: true,
    customClass: "test-ElMessage",
    offset: 100,
    icon: h("img", {
      src: success_ico,
      style: {
        width: "16px",
        height: "16px",
        marginRight: "10px",
      },
    }),
    // duration: 0,
  });
};

export const warningTips = (message: string) => {
  // @ts-ignore
  ElMessage({
    message,
    type: "success",
    dangerouslyUseHTMLString: true,
    customClass: "test-ElMessage",
    offset: 100,
    icon: h("img", {
      src: warning_ico,
      style: {
        width: "16px",
        height: "16px",
        marginRight: "10px",
      },
    }),
    // duration: 0,
  });
};

/* 文件地址下载 */
export const locationDownLoad = (url: string) => {
  if (!url) {
    errorTips("无下载地址");
    return false;
  }
  const link = document.createElement("a");
  link.href = url;
  link.click();
  document.body.appendChild(link);
};

/**
 * 存储sessionStorage
 */
export const setStore = (name: string, content: any) => {
  if (!name) return;
  if (typeof content !== "string") {
    content = JSON.stringify(content);
  }
  window.sessionStorage.setItem(name, content);
};

/**
 * 获取sessionStorage
 */
export const getStore = (name: string) => {
  if (!name) return;
  let content = window.sessionStorage.getItem(name);
  if (!content) return "";
  if (content.indexOf("{") >= 0 || content.indexOf("[") >= 0) {
    return JSON.parse(content);
  } else {
    return content;
  }
};

/**
 * 删除sessionStorage
 */
export const removeStore = (name: string) => {
  if (!name) return;
  window.sessionStorage.removeItem(name);
};

/**
 * 将Base64图片转换为File对象
 * @param {String} base64 - 带前缀的Base64字符串
 * @param {String} [filename='image'] - 生成的文件名
 * @param {String} [mimeType='image/png'] - 文件类型
 * @returns {Promise<File>}
 */
export function base64ToFile(
  base64: string,
  filename = "image",
  mimeType = "image/png"
) {
  // 1. 移除Base64前缀（如果存在）
  const base64Data = base64.split(",")[1] || base64;

  // 2. 转换为二进制字符串
  const binaryStr = atob(base64Data);

  // 3. 转换为Uint8Array
  const length = binaryStr.length;
  const uint8Array = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    uint8Array[i] = binaryStr.charCodeAt(i);
  }

  // 4. 创建File对象
  return new File([uint8Array], `${filename}.${mimeType.split("/")[1]}`, {
    type: mimeType,
  });
}

/**
 * 时间戳格式化
 */
export const getDateTime = function (timestamp: string | undefined) {
  let t = null;
  // 不传值，则获取当前时间
  if (timestamp === undefined) {
    t = new Date();
  } else if (timestamp) {
    t = new Date(parseInt(timestamp));
  }

  if (t) {
    let n: string = t.getFullYear() + "";
    let a: string = t.getMonth() + 1 + "";
    let r: string = t.getDate() + "";
    let o: string = t.getHours() + "";
    let i: string = t.getMinutes() + "";
    let s: string = t.getSeconds() + "";

    parseInt(a) >= 10 || (a = "0" + a),
      parseInt(r) >= 10 || (r = "0" + r),
      parseInt(o) >= 10 || (o = "0" + o),
      parseInt(i) >= 10 || (i = "0" + i),
      parseInt(s) >= 10 || (s = "0" + s);

    return [
      n, // yy 0
      a, // mm 1
      r, // dd 2
      n + "-" + a, // yy-mm 3
      a + "/" + r, // mm/dd 4
      o + ":" + i + ":" + s, // hh:mm:ss 5
      n + "-" + a + "-" + r + " " + o + ":" + i + ":" + s, // yy-mm-dd hh:mm::ss 6
      a + "-" + r + " " + o + ":" + i + ":" + s, // mm-dd hh:mm::ss 7
      n + "-" + a + "-" + r, // yy-mm-dd 8
      n + a + r, // yymmdd 9
      n + a, //yymm 10
      n + "-" + a + "-" + r + " " + o + ":" + i, // yy-mm-dd hh:mm 11
    ];
  } else {
    return ["--", "--", "--", "--", "--", "--", "--", "--", "--"];
  }
};

/**
 * 日期转时间戳
 */
export const getTimestamp = (e: string) => {
  var t;
  if (e) {
    e = e.replace(/-/g, "/");
    t = new Date(e);
  } else t = new Date();
  return t.getTime().toString();
};

// 邮箱校验
export function validateEmail(email: string) {
  const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return regex.test(email);
}

// 判断当前环境
export function detectDevice() {
  const userAgent = navigator.userAgent.toLowerCase();
  if (/android/.test(userAgent)) {
    return "android";
  } else if (/iphone|ipad|ipod/.test(userAgent)) {
    return "ios";
  } else {
    return "pc";
  }
}

export const encrypt = (text: string) => {
  // 1. 使用encodeURIComponent处理特殊字符
  const encodedText = encodeURIComponent(text);
  // 2. 使用btoa进行Base64编码
  const base64Encoded = btoa(encodedText);
  // 3. 将Base64中的'+', '/'替换为英文字符，处理'='
  return base64Encoded
    .replace(/\+/g, "-") // '+' 替换为 '-'
    .replace(/\//g, "_") // '/' 替换为 '_'
    .replace(/=+$/, ""); // 移除末尾的 '='
};

export const decrypt = (encryptedText: string) => {
  // 1. 还原Base64编码中的特殊字符
  let base64Encoded = encryptedText
    .replace(/-/g, "+") // '-' 还原为 '+'
    .replace(/_/g, "/"); // '_' 还原为 '/'

  // 2. 添加被移除的 '='
  while (base64Encoded.length % 4 !== 0) {
    base64Encoded += "=";
  }

  // 3. 使用atob进行Base64解码
  const decodedText = atob(base64Encoded);
  // 4. 使用decodeURIComponent还原原始字符串
  return decodeURIComponent(decodedText);
};

export const isLoginFun = () => {
  let token = getStore("signatrue_token");
  return token ? true : false;
};

/**
 * 去抖动函数
 */
const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number,
  immediate = false
): ((...args: Parameters<T>) => ReturnType<T> | undefined) => {
  let timeout: ReturnType<typeof setTimeout> | null = null;

  return function (
    this: any,
    ...args: Parameters<T>
  ): ReturnType<T> | undefined {
    const context = this;
    const later = () => {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    const callNow = immediate && !timeout;

    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(later, wait);

    if (callNow) return func.apply(context, args);
  };
};

// 节流
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  limit: number
): ((...args: Parameters<T>) => ReturnType<T> | undefined) => {
  let lastFunc: ReturnType<typeof setTimeout> | null = null;
  let lastRan: number | null = null;

  return function (this: any, ...args: Parameters<T>): ReturnType<T> | any {
    const context = this;

    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      if (lastFunc) clearTimeout(lastFunc);

      lastFunc = setTimeout(() => {
        if (Date.now() - lastRan! >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan!)) as ReturnType<typeof setTimeout>;
    }
  };
};

export const setTableCellStyle = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  let style = {
    height: "42px",
    backgroundColor: "#fff",
    color: "#02011B",
  };
  if (rowIndex % 2 !== 0) {
    style.backgroundColor = "#F9F9FB";
  }
  return style;
};

export const setTableHeaderCellStyle = () => {
  return {
    height: "42px",
    backgroundColor: "#F9F9FB",
    color: "#9F9F9F",
    fontSize: "14px",
    fontWeight: "800",
  };
};

export const setTableHeaderRowStyle = () => {
  return {
    height: "42px",
  };
};

/**
 * 防抖
 * @param callback 目标回调
 * @param during 防抖时长 默认1000ms
 * @param immediate 是否立即触发回调 默认为false
 */
export function dou<T extends any[]>(
  callback: { (...args: T): void },
  during = 1000,
  immediate = false
) {
  let timer: number = null!;
  return function (this: any, ...rest: T) {
    if (immediate) {
      // 立即执行
      if (!timer) {
        callback.apply(this, rest);
      }
      if (timer) {
        clearTimeout(timer);
        timer = null!;
      }
      timer = setTimeout(() => {
        timer = null!;
      }, during);
      return;
    }

    if (timer) {
      clearTimeout(timer);
      timer = null!;
    }
    timer = setTimeout(() => {
      callback.apply(this, rest);
      timer = null!;
    }, during);
  };
}

export const onCopy = (val: any) => {
  const textArea = document.createElement("textarea");
  textArea.value = val;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand("copy");
  document.body.removeChild(textArea);
  successTips("复制成功");
};

/**
 * 获取浏览器URL中的查询参数
 * @param url 可选，要解析的URL，默认为当前页面URL
 * @returns 返回解析后的查询参数对象
 */
export function getUrlParams(url?: string): Record<string, string> {
  const targetUrl = url || window.location.href;
  const params: Record<string, string> = {};

  // 处理标准URL参数（如：http://example.com?a=1&b=2）
  const standardQueryIndex = targetUrl.indexOf("?");
  if (standardQueryIndex !== -1) {
    const queryString = targetUrl.slice(standardQueryIndex + 1);
    const hashIndex = queryString.indexOf("#");
    const cleanQuery =
      hashIndex !== -1 ? queryString.slice(0, hashIndex) : queryString;

    cleanQuery.split("&").forEach((param) => {
      if (param) {
        const [key, value] = param.split("=");
        if (key) {
          params[key] = value ? decodeURIComponent(value) : "";
        }
      }
    });
  }

  // 处理哈希路由中的参数（如：http://example.com/#/page?a=1&b=2）
  const hashIndex = targetUrl.indexOf("#");
  if (hashIndex !== -1) {
    const hashPart = targetUrl.slice(hashIndex + 1);
    const hashQueryIndex = hashPart.indexOf("?");

    if (hashQueryIndex !== -1) {
      const hashQueryString = hashPart.slice(hashQueryIndex + 1);

      hashQueryString.split("&").forEach((param) => {
        if (param) {
          const [key, value] = param.split("=");
          if (key) {
            // 优先使用哈希中的参数（覆盖标准URL中的同名参数）
            params[key] = value ? decodeURIComponent(value) : "";
          }
        }
      });
    }
  }

  return params;
}

/* 文件流下载 */
export const BlobDownLoad = (res: any, name: string) => {
  let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(blob);
  link.download = name;
  link.click();
  document.body.appendChild(link);
};

/**
 * 简单的十六进制转 RGB 函数（不支持简写形式如 #FFF）
 */
import type { IpdfItem } from "@/types/pdf";
export const getBgStyle = (schema: IpdfItem) => {
  if (!schema.isBg) return "none";
  const hex = schema.borderColor.replace("#", "");
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);

  return `rgba(${r}, ${g}, ${b}, 0.3)`;
};



/**
 * 简单的十六进制转 RGB 函数（不支持简写形式如 #FFF）
 */

export const getStatusStyle = (hexColor: string) => {
    const hex = hexColor.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);

    return `rgba(${r}, ${g}, ${b}, 0.3)`;
};
